package so.sao.shop.supplier.service.impl;

import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import so.sao.shop.supplier.config.Constant;
import so.sao.shop.supplier.dao.ParameterDao;
import so.sao.shop.supplier.dao.PurchaseDao;
import so.sao.shop.supplier.dao.ReturnAndExchangeDao;
import so.sao.shop.supplier.dao.app.AppApplyForServiceDao;
import so.sao.shop.supplier.domain.Parameter;
import so.sao.shop.supplier.domain.ServiceLogistics;
import so.sao.shop.supplier.pojo.Result;
import so.sao.shop.supplier.pojo.input.DeliverGoodsInput;
import so.sao.shop.supplier.pojo.input.ExchangePurchaseItemInput;
import so.sao.shop.supplier.pojo.input.ReturnPurchaseSelectInput;
import so.sao.shop.supplier.pojo.output.ExchangePurchaseItemOutput;
import so.sao.shop.supplier.pojo.output.ReturnAndExchangeDetailOutput;
import so.sao.shop.supplier.pojo.vo.RefuseOrderImgVo;
import so.sao.shop.supplier.pojo.vo.ReturnPurchasesVo;
import so.sao.shop.supplier.service.ReturnAndExchangeService;
import so.sao.shop.supplier.util.BeanMapper;
import so.sao.shop.supplier.util.DataCompare;
import so.sao.shop.supplier.util.Ognl;
import so.sao.shop.supplier.util.PageTool;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>Version: New shop-1.2.0 V1.1.0 </p>
 * <p>Title: ReturnAndExchangeServiceImpl</p>
 * <p>Description: 订单退换货serviceImpl</p>
 *
 * @author: zhaoyan
 * @Date: Created in 2017/11/29 10:40
 */
@Service
public class ReturnAndExchangeServiceImpl implements ReturnAndExchangeService {
    @Autowired
    private ReturnAndExchangeDao returnAndExchangeDao;
    @Autowired
    private AppApplyForServiceDao appApplyForServiceDao;
    @Autowired
    private PurchaseDao purchaseDao;
    @Autowired
    private ParameterDao parameterDao;

    /**
     * 查询换货列表，供应商与管理员通用
     * @param exchangePurchaseItemInput 换货列表入参对象
     * @return result
     */
    @Override
    public Result searchExchange(ExchangePurchaseItemInput exchangePurchaseItemInput) {
        //起始时间不能大于终止时间
        String createAtMessage = DataCompare.createAtCheck(exchangePurchaseItemInput.getBeginApplyForTime(),exchangePurchaseItemInput.getEndApplyForTime());
        if(!"".equals(createAtMessage)){
            return Result.fail(createAtMessage);
        }
        //设置分页参数
        PageTool.startPage(exchangePurchaseItemInput.getPageNum(), exchangePurchaseItemInput.getPageSize());
        List<ExchangePurchaseItemOutput> exchangeList = returnAndExchangeDao.findExchange(exchangePurchaseItemInput);
        PageInfo<ExchangePurchaseItemOutput> pageInfo = new PageInfo<ExchangePurchaseItemOutput>(exchangeList);
        return Result.success(Constant.MessageConfig.MSG_SUCCESS, pageInfo);
    }

    /**
     * 查询退换货详情信息
     * @param detailsId 详情编号ID
     * @return result
     */
    @Override
    public Result getReturnAndExchangeDetail(Long detailsId) {
        //查询退换货详情信息
        ReturnAndExchangeDetailOutput detail = returnAndExchangeDao.findDetail(detailsId);
        if (Ognl.isNotNull(detail) && Ognl.isNotNull(detail.getGoodsDiscount())) {
            BigDecimal price = detail.getGoodsUnitPrice().multiply(new BigDecimal(detail.getGoodsNumber()));
            //商品总额==（商品单价*商品数量）-抵扣优惠
            detail.setGoodsTotalPrice(price.subtract(detail.getGoodsDiscount()));
            //实付金额==（商品单价*商品数量）-抵扣优惠
            detail.setTotalPrice(price.subtract(detail.getGoodsDiscount()));
        }
        //查询对应的拒收图片
        List<RefuseOrderImgVo> refuseOrderImgList = appApplyForServiceDao.searchRefuseOrderImgs(detailsId);
        detail.setImagesList(refuseOrderImgList);
        return Result.success(Constant.MessageConfig.MSG_SUCCESS,detail);
    }
	
	/**
     * 退货列表
     * @param returnPurchaseSelectInput 退货列表入参对象
     * @return Result
     */
    @Override
    public Result searchOrders(ReturnPurchaseSelectInput returnPurchaseSelectInput) {
        String reMessage1 = DataCompare.createAtCheck(returnPurchaseSelectInput.getBeginDate(),returnPurchaseSelectInput.getEndDate());
        String reMessage2 = DataCompare.createAtCheck(returnPurchaseSelectInput.getOrderPaymentBeginTime(),returnPurchaseSelectInput.getOrderPaymentEndTime());
        String reMessage3 = DataCompare.createAtCheck(returnPurchaseSelectInput.getOrderReceiveBeginTime(),returnPurchaseSelectInput.getOrderReceiveEndTime());
        //退货申请时间起始时间和结束时间对比
        if(!(StringUtils.isBlank(reMessage1) || StringUtils.isBlank(reMessage2) || StringUtils.isBlank(reMessage3))){
            return Result.fail(reMessage1);
        }
        //对比开始金额和结束金额
        if (DataCompare.compareMoney(returnPurchaseSelectInput.getBeginMoney(), returnPurchaseSelectInput.getEndMoney())) {
            return Result.fail(Constant.MessageConfig.MoneyNOTLate);
        }
        PageTool.startPage(returnPurchaseSelectInput.getPageNum(), returnPurchaseSelectInput.getPageSize());
        List<ReturnPurchasesVo> returnList = returnAndExchangeDao.findPage(returnPurchaseSelectInput);
        //设置分页
        PageInfo<ReturnPurchasesVo> pageInfo = new PageInfo<ReturnPurchasesVo>(returnList);
        return Result.success(Constant.MessageConfig.MSG_SUCCESS,pageInfo);
    }
	
    /**
     * 子订单退换货审核
     *
     * @param detailsId    详情编号ID
     * @param status       审核结果状态
     * @param refuseReason 审核拒绝原因描述
     * @return result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result auditPurchaseItem(Long detailsId, int status, String refuseReason) {
        if (returnAndExchangeDao.findStatusByDetailsId(detailsId) != Constant.OrderDetailsStatusConfig.APPLYFORING) {
            return Result.fail("该订单只有在待换货或待退货状态时才可进行审核操作！");
        }
        Date checkTime = new Date();
        returnAndExchangeDao.auditPurchaseItem(detailsId, status, refuseReason, checkTime);
        //退换货审核拒绝时，更新大订单的状态
        if (status == Constant.OrderDetailsStatusConfig.REJECT) {
            //检查是否更新主订单状态至已完成
            String orderId = returnAndExchangeDao.findOrderIdByDetailsId(detailsId);
            boolean flag = checkPurchaseStatus(orderId);
            if (flag) {
                List<String> list = new ArrayList<>();
                list.add(orderId);
                purchaseDao.updateRefundOrderStatus(list, Constant.OrderStatusConfig.RECEIVED,new Date());
            }
        }
        return Result.success("审核成功！");
    }

    /**
     * 添加订单换货寄出货物流信息
     *
     * @param deliverGoodsInput 物流对象入参
     * @return result
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deliverGoods(DeliverGoodsInput deliverGoodsInput) {
        if (returnAndExchangeDao.findStatusByDetailsId(deliverGoodsInput.getDetailsId()) != Constant.OrderDetailsStatusConfig.RETURNOREXCHANGE) {
            return Result.fail("请等待买家发货并确认后再发货！");
        }
        if (returnAndExchangeDao.countReturnDeliverGoods(deliverGoodsInput.getDetailsId()) > 0) {
            return Result.fail("该订单已存在换货寄出物流信息，请勿重复填写！");
        }
        //复制对象到ServiceLogistics的domain对象
        ServiceLogistics serviceLogistics = BeanMapper.map(deliverGoodsInput, ServiceLogistics.class);
        //设置物流售后类型, 0-门店发货, 1-供应商发货
        serviceLogistics.setLogisticsType(1);
        serviceLogistics.setCreateTime(new Date());
        serviceLogistics.setUpdateTime(new Date());
        //添加订单换货寄出货物流信息
        returnAndExchangeDao.deliverGoods(serviceLogistics);
        //更新换货订单发货时间与订单状态
        returnAndExchangeDao.updateSendTimeAndStatus(deliverGoodsInput.getDetailsId(), serviceLogistics.getCreateTime());
        //检查是否更新主订单状态至已完成
        String orderId = returnAndExchangeDao.findOrderIdByDetailsId(deliverGoodsInput.getDetailsId());
        boolean flag = checkPurchaseStatus(orderId);
        if (flag) {
            List<String> list = new ArrayList<>();
            list.add(orderId);
            purchaseDao.updateRefundOrderStatus(list, Constant.OrderStatusConfig.RECEIVED,new Date());
        }
        return Result.success("已成功发货！");
    }

    /**
     * 校验子订单对应的主订单内是否已所有到达最终状态
     * 判断确认售货时间是否已超过五天/子订单无退换货进行/子订单均处于终态===>返回true,否则返回false
     *
     * @param orderId 订单ID
     * @return boolean
     */
    private boolean checkPurchaseStatus(String orderId) {
        //查询//判断确认售货时间是否已超过五天
        Date orderReceiveTime = returnAndExchangeDao.findOrderReceiveTime(orderId);
        if (Ognl.isEmpty(orderReceiveTime)) {
            return false;
        }
        //判断确认售货时间是否已超过五天
        Long timeDiff = System.currentTimeMillis() - orderReceiveTime.getTime();
        Long times = timeDiff / (3600 * 1000);
        //获取数据库中的订单申请售后时间
        List<Parameter> parameterList = parameterDao.selectByKey("service_time");
        int serviceTime = Integer.parseInt(parameterList.get(0).getParameterValue());
        if (times < (serviceTime * 24 - 1)) {
            return false;
        }
        //查询主订单下所有子订单状态
        List<Integer> list = returnAndExchangeDao.findAllStatusByDetailsId(orderId);
        for (Integer i : list) {
            if (!i.equals(Constant.OrderDetailsStatusConfig.COMPLATE) && !i.equals(Constant.OrderDetailsStatusConfig.REJECT)
                    && !i.equals(Constant.OrderDetailsStatusConfig.REFUNDED) && !i.equals(Constant.OrderDetailsStatusConfig.CANCEL_ORDER)) {
                return false;
            }
        }
        return true;
    }
}
